// Copyright (C) 2008 Taylor L. Riche <riche@cs.utexas.edu>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//

#ifndef OPERATOR_H_
#define OPERATOR_H_

#include <assert.h>
#include <vector>
#include <map>
#include <queue>
#include <utility>
#include <list>
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include "CoreOp.h"
#include "RCon.h"
#include "RData.h"
#include "ProcElement.h"
#include "MonitorRequest.h"
#include "Mutex.h"
#include "System.h"

namespace lagniappe
{

class RCon;
class ProcElement;
class CoreOp;
class System;
class CommChannel;

typedef unsigned long FlowID;

class Operator : public CoreOp
{
protected:
	std::string name;
	std::vector<ProcElement *> procList;
	std::vector<ProcElement *>::iterator iter;
	unsigned long count;
	void LC_handleMonitor(RData * data);
	void sendMonitorReq(ReqType const & rt, void * v = NULL);
	Mutex * mutex;
	System * system;
	bool underConsideration;
	ProcElement * lockedProc;
	// TLR: OPT
	std::map<uint32_t, double> profMap;
	bool inProf;
	void profileRConEnqueue(ProcElement * proc, RCon * rcon);
	void profileMeasure(ProcElement * proc, RCon * rcon);
	Mutex * getNewMutex();
	virtual void reassignFlow(ProcElement * proc) {}
public:
	Operator(bool prof = false);
	Operator(std::string s, Mutex * m, System * sys, bool prof = false);
	virtual ~Operator();
	void schedule(ProcElement * p, bool initProc = false);
	void setMutex(Mutex * m) {mutex = m;}
	virtual ProcElement * getProc(RCon * rcon);
	virtual void run(RCon * rcon);
	virtual void run(std::queue<RCon *> * rconQueue);
	std::string getName() {return name;}
	void profile(System * sys);
	void writeProfileInfo(std::ofstream & outfile);
	virtual void registerPorts(lagniappe::CommChannel * chan) = 0;
	virtual std::list<RCon *> * generateRequestList() {assert(false); return NULL;}
	//virtual int getQueueThreshold() {return -1;}
};

}

#endif /*OPERATOR_H_*/
